# coding=utf-8
# -*- coding: UTF-8 -*-
#
# This file is part of the kernelstudio package.
#
# (c) 2014-2025 zlin <admin@kernelstudio.com>
#
# For the full copyright and license information, please view the LICENSE file
# that was distributed with this source code.
import datetime

from flask import request
from flask_restful import reqparse

from ksai.models.document_labels import DocumentLabelsModelQuery, DocumentLabelsModel
from ksai.services.document_labels import DocumentLabelsService
from ksai.web.api import ApiResource


def parse_app_request(label):
    parser = reqparse.RequestParser()
    parser.add_argument("uuid", type=str, required=False, nullable=True, location="json", )
    parser.add_argument("parent_uuid", type=str, required=False, nullable=True, location="json", )
    parser.add_argument("name", type=str, required=True, nullable=False, location="json", )
    parser.add_argument("type", type=str, required=True, nullable=False, location="json", )
    args = parser.parse_args()

    label.uuid = args['uuid']
    label.parent_uuid = args['parent_uuid']
    label.name = args['name']
    label.type = args['type']
    return label


class DocumentLabelsController(ApiResource):

    def get(self, query=DocumentLabelsModelQuery()):
        query.init(request.args, 15)
        DocumentLabelsService.find_by_query(query)

        return self.make_success(result=query)

    def post(self):
        label = DocumentLabelsModel()
        label = parse_app_request(label)

        DocumentLabelsService.save(label)
        return self.make_success(label)


class DocumentLabelsUpdateDeleteController(ApiResource):

    def put(self, uuid):
        saved = DocumentLabelsService.find_one_by_uuid(uuid)
        label = parse_app_request(saved)
        label.updated_at = datetime.datetime.now()

        DocumentLabelsService.save(label)

        return self.make_success(label)

    def delete(self, uuid):
        saved = DocumentLabelsService.find_one_by_uuid(uuid)
        saved.deleted_at = datetime.datetime.now()
        DocumentLabelsService.save(saved)
        return self.make_success(saved)
